package com.shwread.android.qysw.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.base.BaseActicity;
import com.ciko.code.logic.bean.AddressBookInfo;
import com.ciko.code.logic.dao.AddressBookInfoDao;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000192.R;
import com.shwread.android.ui.customview.MyExpandableListView;
import com.shwread.android.ui.page.chat.adapter.SelectApproverAdapter;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.Logger;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import logic.bean.ContactYellowPageInfo;
import logic.bean.ContractInfo;
import logic.bean.GroupBean;
import logic.dao.GroupDao;

/*
* 选择审批人
*
* */
public class SelectApproverActivity extends BaseActicity implements
        View.OnClickListener {
    public static int[] isClose;
    private PullToRefreshScrollView contentView;
    private MyExpandableListView listView;
    private TextView tvSearch;
    private List<GroupBean> groups = new ArrayList<GroupBean>();
    private HashMap<String, List<AddressBookInfo>> contacts = new HashMap<String, List<AddressBookInfo>>();
    private String ypUrl;
    private static long lastTimeStamp;

    private SelectApproverAdapter adapter;
    private ImageView img_back;
    //数据库相关
    private GroupDao groupDao;
    private AddressBookInfoDao addressBookInfoDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        unableNav();

    }


    @Override
    protected void initTopBar() {
//        setTitle("选择审批人");
//        enableNavLeftImg();
    }

    /**
     * 下拉刷新
     */
    private void refrush() {
        listView.setVisibility(View.GONE);
        initDates();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.et_contact_search:
                Intent searchIntent = new Intent(SelectApproverActivity.this, SearchApproverActivity.class);
                startActivity(searchIntent);
                break;

        }
    }


    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_select_approver);
        groupDao = GroupDao.getInstance(SelectApproverActivity.this);
        addressBookInfoDao = AddressBookInfoDao.getInstance(SelectApproverActivity.this);
        lastTimeStamp = QyreaderPerferencesUtil.getInstance(SelectApproverActivity.this, "0").getContactLastTimeStamp();

    }

    @Override
    protected void initView() {
        img_back = (ImageView) findViewById(R.id.img_back);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        contentView = (PullToRefreshScrollView) findViewById(R.id.contact_psview);
        PullToRefreshUtil.initLabel(SelectApproverActivity.this, contentView);
        tvSearch = (TextView) findViewById(R.id.et_contact_search);
        listView = (MyExpandableListView) findViewById(R.id.contacts_list);
       /* listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {

                String contactName= contacts.get(i).get(i1).getContactName();
                Intent intent = new Intent();
                intent.putExtra("contactName",contactName);
                setResult(RESULT_OK,intent);
                finish();
                return true;
            }
        });*/
    }

    @Override
    protected void initAdapter() {

    }

    @Override
    protected void initDates() {
//        Date date = new Date();
//        date.setYear(2015);
//        Log.e("时间戳",date.getTime()+"");
        NewActionHelp.qryEnterpriseAddressBookList(SelectApproverActivity.this, lastTimeStamp, new GetAddressBookListHandler());
        progressDialog2.show();
        NewActionHelp.qryEnterpriseYellowPage(SelectApproverActivity.this, new GetYellowPageHandler());
    }


    public class GetYellowPageHandler
            extends
            ObjectHttpResponseHandler<ContactYellowPageInfo> {

        @Override
        public Type getType() {
            return new TypeToken<ContactYellowPageInfo>() {
            }.getType();
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
            if (progressDialog2.isShowing()) {
                progressDialog2.dismiss();
            }
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, ContactYellowPageInfo arg2, String arg3) {
            if (arg2 != null) {
                ypUrl = arg2.getUrl();
            }
            if (progressDialog2.isShowing()) {
                progressDialog2.dismiss();
            }
        }
    }

    public class GetAddressBookListHandler
            extends
            ObjectHttpResponseHandler<ContractInfo> {

        @Override
        public Type getType() {
            return new TypeToken<ContractInfo>() {
            }.getType();
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
            if (progressDialog2.isShowing()) {
                progressDialog2.dismiss();
            }
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, ContractInfo arg2, String arg3) {
            if (arg2 != null) {
                groups = arg2.getGroupList();
                lastTimeStamp = arg2.getLastTimeStamp();
                Logger.d("group size:" + groups.size());
            }
            QyreaderPerferencesUtil.getInstance(SelectApproverActivity.this, "0").setContactLastTimeStamp(lastTimeStamp);

            putDataToDB();
            getDataFromDb();
            sortGroups();
            sortContacts();
            int p = 0;
            isClose = new int[groups.size()];
            for (GroupBean group : groups) {
                contacts.put(group.getName(), group.getAddressBookList());
                isClose[p] = 0;
                p++;
            }

            adapter = new SelectApproverAdapter(SelectApproverActivity.this, listView, groups, contacts);
            listView.setAdapter(adapter);

            listView.setGroupIndicator(null);
            listView.setFocusable(false);
            listView.setFocusableInTouchMode(false);
            contentView.onRefreshComplete();
            listView.setVisibility(View.VISIBLE);
            if (progressDialog2.isShowing()) {
                progressDialog2.dismiss();
            }

        }

    }

    private void sortContacts() {
        List<AddressBookInfo> contacts = new ArrayList<AddressBookInfo>();
        AddressBookInfo contact = new AddressBookInfo();
        for (GroupBean group : groups) {
            contacts = group.getAddressBookList();
            for (int i = 0; i < contacts.size() - 1; i++) {
                for (int j = i; j < contacts.size(); j++) {
                    if (contacts.get(i).getSortNum() > contacts.get(j).getSortNum()) {
                        contact = contacts.get(i);
                        contacts.set(i, contacts.get(j));
                        contacts.set(j, contact);
                    }
                }
            }
            group.setAddressBookList(contacts);
        }
    }

    private void sortGroups() {
        GroupBean bean = new GroupBean();
        for (int i = 0; i < groups.size() - 1; i++) {
            for (int j = i + 1; j < groups.size(); j++) {
                if (groups.get(i).getSortNum() > groups.get(j).getSortNum()) {
                    bean = groups.get(i);
                    groups.set(i, groups.get(j));
                    groups.set(j, bean);
                }
            }
        }
    }

    private void getDataFromDb() {
        groups.clear();
        List<GroupBean> dbGroups = new ArrayList<GroupBean>();
        dbGroups = groupDao.getAll();
        for (int i = 0; i < dbGroups.size(); i++) {
            List<AddressBookInfo> addressBookList = new ArrayList<AddressBookInfo>();
            List<AddressBookInfo> dbList = new ArrayList<AddressBookInfo>();
            dbList = addressBookInfoDao.getListByGroupId(dbGroups.get(i).getGroupId());
            for (AddressBookInfo info : dbList) {
                if (info.getIsDelete().equals("n")) {
                    addressBookList.add(info);
                }
            }
            dbGroups.get(i).setAddressBookList(addressBookList);
        }
        for (GroupBean group : dbGroups) {
            if (group.getAddressBookList() != null && group.getAddressBookList().size() != 0) {
                groups.add(group);
            }
        }
    }

    private void putDataToDB() {
        for (GroupBean group : groups) {
            if (groupDao.getById(group.getGroupId()) != null) {
                groupDao.update(group);
            } else {
                groupDao.add(group);
            }
            for (AddressBookInfo addressBookInfo : group.getAddressBookList()) {
                if (addressBookInfoDao.getById(addressBookInfo.getContactId(), group.getGroupId()) != null) {
                    addressBookInfoDao.update(addressBookInfo);
                } else {
                    addressBookInfoDao.add(addressBookInfo);
                }
            }
        }
    }

    @Override
    protected void initListener() {

        tvSearch.setOnClickListener(this);
        contentView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (contentView.isHeaderShown()) {
                    refrush();
                } else if (contentView.isFooterShown()) {
                    contentView.onRefreshComplete();
                }
            }

        });
    }
}
